class GenreLinksController < ApplicationController
  #filter_access_to :all
  before_filter :find_item
  
  #If AJAX request, use the slim layout (no header or footer)
  #Otherwise use the main layout
  layout Proc.new { |controller| controller.request.xhr? ? 'slim' : 'main' }

  #
  #
  def new
    if params[:artist_id]
      @create_url = search_artist_genre_links_path
    elsif params[:edition_id]
      @create_url = search_edition_genre_links_path
    elsif params[:song_id]
      @create_url = search_song_genre_links_path
    end

    render :new
  end

  def search
	@genres = Genre.search(params[:search])
	
    respond_to do |format|
	  format.html { }
	  format.js {
	    render :update do |page|
		  page.replace_html("genre-search-results", :partial => 'results',
		                                            :locals => { :genres => @genres })
		end
	  }
	end
  end
  
  #
  #
  def create  
    if params[:genre_id]
	  genre_add = Genre.find(params[:genre_id])
	  @item.genres<<genre_add unless @item.genres.exists?(genre_add)
	elsif params[:genre_name]
	  @item.genres.build(:name => params[:genre_name])
	end
	
	respond_to do |format|
	  if @item.save
	    flash[:notice] = 'Genre successfully added.'
		format.html { redirect_to_request_uri }
	  else
	    flash[:error] = @item.errors.full_messages
		format.html { redirect_to_request_uri }
	  end
	end
    
  end

  #
  #
  def destroy
    #Find and delete the genre
    genre = Genre.find(params[:genre_id])
    @item.genres.delete(genre)

    #Hack to create this edit to get around an issue with the
    # after_destroy callback
    entry = Hash.new
    entry.store("unlinked genre", [genre.name])
    Edit.create_edit(entry, @item)

    respond_to do |format|
      if @item.save!
        format.html { redirect_to_request_uri }
      end
    end
  end

  private

  def find_item
    if params[:artist_id]
      @item = Artist.find(params[:artist_id])
    elsif params[:edition_id]
      @item = Edition.find(params[:edition_id])
    elsif params[:song_id]
      @item = Song.find(params[:song_id])
    end
  end

end
